package cn.iocoder.yudao.module.resource.controller.admin.tag;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.redis.core.RedisPublishClient;
import cn.iocoder.yudao.module.resource.controller.admin.tag.vo.TagPageReqVO;
import cn.iocoder.yudao.module.resource.controller.admin.tag.vo.TagRespVO;
import cn.iocoder.yudao.module.resource.controller.admin.tag.vo.TagSaveReqVO;
import cn.iocoder.yudao.module.resource.dal.dataobject.tag.TagDO;
import cn.iocoder.yudao.module.resource.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.resource.service.audiomark.AudioMarkService;
import cn.iocoder.yudao.module.resource.events.RefreshTagEvent;
import cn.iocoder.yudao.module.resource.service.tag.TagService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 标签")
@RestController
@RequestMapping("/lm/tag")
@Validated
public class TagController {

    @Resource
    private TagService tagService;
    @Resource
    private AudioMarkService audioMarkService;

    @Resource
    private RedisPublishClient redisPublishClient;

    private void sendUpdateEvent() {
        RefreshTagEvent refreshTagEvent = new RefreshTagEvent();
        redisPublishClient.publishMsg(refreshTagEvent);
    }

    @PostMapping("/create")
    @Operation(summary = "创建标签")
    @PreAuthorize("@ss.hasPermission('lm:tag:create')")
    public CommonResult<Integer> createTag(@Valid @RequestBody TagSaveReqVO createReqVO) {
        CommonResult<Integer> success = success(tagService.createTag(createReqVO));
        sendUpdateEvent();
        return success;
    }

    @PutMapping("/update")
    @Operation(summary = "更新标签")
    @PreAuthorize("@ss.hasPermission('lm:tag:update')")
    public CommonResult<Boolean> updateTag(@Valid @RequestBody TagSaveReqVO updateReqVO) {
        tagService.updateTag(updateReqVO);
        this.sendUpdateEvent();
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除标签")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('lm:tag:delete')")
    public CommonResult<Boolean> deleteTag(@RequestParam("id") Integer id) {
        // 如果有标记的音频，不能删除
        if (this.audioMarkService.isHaveMarkAudioWithTagId(id)) {
            throw new ServiceException(ErrorCodeConstants.TAG_HAD_MARK_AUDIO);
        }
        tagService.deleteTag(id);
        this.sendUpdateEvent();
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得标签")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('lm:tag:query')")
    public CommonResult<TagRespVO> getTag(@RequestParam("id") Integer id) {
        TagDO tag = tagService.getTag(id);
        return success(BeanUtils.toBean(tag, TagRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得标签分页")
    @PreAuthorize("@ss.hasPermission('lm:tag:query')")
    public CommonResult<PageResult<TagRespVO>> getTagPage(@Valid TagPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<TagDO> pageResult = tagService.getTagPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, TagRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出标签 Excel")
    @PreAuthorize("@ss.hasPermission('lm:tag:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTagExcel(@Valid TagPageReqVO pageReqVO,
                               HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TagDO> list = tagService.getTagPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "标签.xls", "数据", TagRespVO.class,
                BeanUtils.toBean(list, TagRespVO.class));
    }

}